package com.kust.smarthome.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kust.smarthome.web.mapper.AirConditionerMapper;
import com.kust.smarthome.web.mapper.DeviceStateMapper;
import com.kust.smarthome.web.model.AirConditioner;
import com.kust.smarthome.web.model.DeviceState;
import com.kust.smarthome.web.service.IAirConditionerService;
import com.kust.smarthome.web.vo.DeviceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AirConditionerImpl extends ServiceImpl<AirConditionerMapper, AirConditioner> implements IAirConditionerService {
    @Autowired
    private AirConditionerMapper airConditionerMapper;

    @Autowired
    private DeviceStateMapper deviceStateMapper;

    @Override
    public int insert(AirConditioner airConditioner) {
        return airConditionerMapper.insert(airConditioner);
    }

    @Override
    public List<AirConditioner> getByUserId(Integer userId) {
        QueryWrapper<AirConditioner> query = new QueryWrapper<>();
        query.eq("user_id",userId);
        return airConditionerMapper.selectList(query);
    }

    @Override
    public List<AirConditioner> add(Integer userId, DeviceVo deviceVo) {
        QueryWrapper<AirConditioner> query = new QueryWrapper<>();
        query.eq("user_id",userId);
        List<AirConditioner> list = airConditionerMapper.selectList(query);

        LocalDateTime now = LocalDateTime.now();
        if (list.size() < 3) {
            AirConditioner airConditioner = new AirConditioner()
                    .setId(deviceVo.getId())
                    .setUrl("")
                    .setContent("这是一个空调")
                    .setState(0)
                    .setCreated(now)
                    .setUserId(userId)
                    .setRoomId(deviceVo.getRoomId());
            airConditionerMapper.insert(airConditioner);
            list.add(airConditioner);

            DeviceState deviceState = new DeviceState()
                    .setDeviceId(deviceVo.getId())
                    .setTypeId(6)
                    .setIsUpdate(0);

            deviceStateMapper.insert(deviceState);

            return list;
        }
        return list;
    }

    @Override
    public List<DeviceState> findOperationList(Integer deviceId, Integer typeId) {
        return airConditionerMapper.getOperationList(deviceId,typeId);

    }

    @Override
    public boolean setupdate(Integer id) {
        airConditionerMapper.changeUpdate(id);
        return true;
    }

}
